package com.cykj.pos.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.common.utils.StringUtils;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.BizAgentidAppkeyDTO;
import com.cykj.pos.domain.dto.RiskControlDTO;
import com.cykj.pos.domain.dto.SubmitGrantDetailDTO;
import com.cykj.pos.mapper.BizMerchantReceiverMapper;
import com.cykj.pos.mapper.BizPosMachineMapper;
import com.cykj.pos.pojo.UserSign;
import com.cykj.pos.service.*;
import com.cykj.pos.service.impl.BizMerchantReceiverServiceImpl;
import com.cykj.pos.service.impl.PosV1AppMerApiServiceImpl;
import com.cykj.pos.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Wangjiaqi
 * @date 2022/07/06
 * 薪龙签约提现
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/xinLong/signed/withdrawal" )
@Api(tags = "薪龙签约提现")
public class XinLongSignedWithdrawalController {

    private static Logger logger = LoggerFactory.getLogger(SaasSignatureUtil.class);

    private final BizMerchantReceiverServiceImpl bizMerchantReceiverService;

    private final IBizMerchantService bizMerchantService;

    private final IBizMerchantReceiverService iBizMerchantReceiverService;

    private final IBizMicroInfoService bizMicroInfoService;

    private final IBizMessageRecordsService bizMessageRecordsService;

    private final IBizWalletService walletService;

    private final BizMerchantReceiverMapper bizMerchantReceiverMapper;

    private final BizPosMachineMapper posMachineMapper;

    private final PosV1AppMerApiServiceImpl posV1AppMerApiServiceimpl;

    private final PosPCommonParamConfig PosPCommonParamConfig;

    @PostMapping("/echoReceiver")
    @Transactional
    public AjaxResult echoReceiver(@RequestBody BizMerchant bizMerchant){
        AjaxResult ajaxResult = AjaxResult.success("查询商户是否签约");
//        SysUser user= SecurityUtils.getLoginUser().getUser();
//        if(posMachineMapper.getDeptid(user.getUserId())!=117){
//            ajaxResult.put("data","2");
//            ajaxResult.put("ret_msg","商户已签约");
//            return ajaxResult;
//        }
        //根据商户id查询部门id 查代付类型
        BizMerchantReceiver bizMerchantReceiver;
        String deptId = bizMicroInfoService.getDeptIdByuserId(bizMerchant.getUserId().toString());
        String dftype =  bizMicroInfoService.getDfTypeByMerchId(bizMerchant.getUserId().toString());
        bizMerchant.setDeptId(deptId);
        if("A".equals(dftype)) {// A  是银付通
            bizMerchantReceiver = bizMerchantService.selectBizMerchantReceiver(bizMerchant);
            if(bizMerchantReceiver != null && "2".equals(bizMerchantReceiver.getContractStatus())){
                return AjaxResult.success("已签约","2");
            }
            String merchId = bizMerchantService.selectMerchId(bizMerchant.getUserId().toString());
            BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(Long.parseLong(merchId));
            return goSign(bizMicroInfoByMerchId,bizMerchant.getUserId(),bizMerchantReceiver,deptId);
//            if (bizMerchantReceiver == null) {
//                String merchId = bizMerchantService.selectMerchId(bizMerchant.getUserId().toString());
//                BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(Long.parseLong(merchId));
//                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                BizMerchantReceiver receiver = new BizMerchantReceiver();
//                receiver.setMerchId(Long.parseLong(merchId));
//                receiver.setUserId(bizMerchant.getUserId());
//                receiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
//                receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
//                receiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
//                receiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());
//                receiver.setContractStatus("2");
//                receiver.setYlgSignStatus("1");
//                receiver.setCreateTime(format.format(new Date()));
//                //先新增一条商户下发收款者
//                iBizMerchantReceiverService.intserReceiverService(receiver);
//                ajaxResult.put("data", "2");
//                ajaxResult.put("ret_msg", "商户已签约");
//                return ajaxResult;
//            }else{
//                ajaxResult.put("data", "2");
//                ajaxResult.put("ret_msg", "商户已签约");
//                return ajaxResult;
//            }

//            if(bizMerchantReceiver.getYlgSignStatus().equals("0") && bizMerchantReceiver.getContractStatus().equals("2")) {
//                // 原签约签约成功,  新签约未签约 去签约
//                String merchId = bizMerchantService.selectMerchId(bizMerchantReceiver.getUserId().toString());
//                bizMerchantReceiver.setMerchId(Long.parseLong(merchId));
//                BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(Long.parseLong(merchId));
//                String result = ylgSign(bizMicroInfoByMerchId);
//                SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                JSONObject json = JSONObject.parseObject(result);
//                if(json.get("code").equals("0000")){
//                    // 签约成功
//                    BizMerchantReceiver bizMerchantReceiver1 = iBizMerchantReceiverService.selectBizMerchantReceiverByMerchId(bizMerchantReceiver);
//                    if (bizMerchantReceiver1==null){
//                        //查询出该商户
//                        BizMerchantReceiver receiver = new BizMerchantReceiver();
//                        receiver.setMerchId(Long.parseLong(merchId));
//                        receiver.setUserId(bizMerchantReceiver.getUserId());
//                        receiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
//                        receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
//                        receiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
//                        receiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());
//                        receiver.setContractStatus("2");
//                        receiver.setYlgSignStatus("1");
//                        receiver.setCreateTime(format.format(new Date()));
//                        //先新增一条商户下发收款者
//                        iBizMerchantReceiverService.intserReceiverService(receiver);
//                        ajaxResult.put("data","2");
//                        ajaxResult.put("ret_msg","商户已签约");
//                        return ajaxResult;
//                    }else {
//                        BizMerchantReceiver receiver = new BizMerchantReceiver();
//                        receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
//                        receiver.setContractStatus("2");
//                        receiver.setYlgSignStatus("1");
//                        iBizMerchantReceiverService.updateReceiver(receiver);
//                        ajaxResult.put("data","2");
//                        ajaxResult.put("ret_msg","商户已签约");
//                        return ajaxResult;
//                    }
//                }else{
//                    ajaxResult.put("code","500");
//                    ajaxResult.put("msg","签约失败:"+json.get("content"));
//                    return AjaxResult.success(ajaxResult);
//                }
//            }else if(bizMerchantReceiver.getYlgSignStatus().equals("1") && bizMerchantReceiver.getContractStatus().equals("2")){
//                ajaxResult.put("data","2");
//                ajaxResult.put("ret_msg","商户已签约");
//                return ajaxResult;
//            }else{
//                ajaxResult.put("data","0");
//                ajaxResult.put("ret_msg","商户待签约");
//                return ajaxResult;
//            }
        }else{  //  这里是 李志
            bizMerchantReceiver = bizMerchantService.selectBizMerchantReceiverTypeB(bizMerchant);
            if (bizMerchantReceiver == null){
                ajaxResult.put("data","0");
                ajaxResult.put("ret_msg","商户待签约");
                return ajaxResult;
            }
            if (bizMerchantReceiver.getContractStatus().equals("0")){
                ajaxResult.put("data","0");
                ajaxResult.put("ret_msg","商户待签约");
                return ajaxResult;
            }else if(bizMerchantReceiver.getContractStatus().equals("1")){
                ajaxResult.put("data","1");
                ajaxResult.put("ret_msg","商户签约中");
                return ajaxResult;
            }else if (bizMerchantReceiver.getContractStatus().equals("3")){
                ajaxResult.put("data","3");
                ajaxResult.put("ret_msg","商户签约失败");
                return ajaxResult;
            }else if (bizMerchantReceiver.getContractStatus().equals("4")){
                ajaxResult.put("data","4");
                ajaxResult.put("ret_msg","商户拒签");
                return ajaxResult;
            }else {
                ajaxResult.put("data","2");
                ajaxResult.put("ret_msg","商户已签约");
                return ajaxResult;
            }
        }
    }


    private AjaxResult goSign(BizMicroInfo bizMicroInfoByMerchId,Long userId,BizMerchantReceiver bizMerchantReceiver1,String deptId){
        BizMerchantReceiver bizMerchantReceiver =  new BizMerchantReceiver();
        UserSign userSign = new UserSign();
        userSign.setRealName(bizMicroInfoByMerchId.getMerchIdcardName());
        userSign.setCardId(bizMicroInfoByMerchId.getMerchIdcard());
        userSign.setPhoneNo(bizMicroInfoByMerchId.getMerchBankMobile());
        bizMerchantReceiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
        bizMerchantReceiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
        bizMerchantReceiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
        bizMerchantReceiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());
        bizMerchantReceiver.setMerchId(bizMicroInfoByMerchId.getMerchId());
        bizMerchantReceiver.setUserId(userId);
        //根据部门查代付主体
        BizBehalfPayment bizBehalfPayment = bizMicroInfoService.getBehalfPaymentByDeptId(deptId);
        Map<String, Object> map = HqyApiUtilsV2.callHqyMerApi(UUID.randomUUID().toString(),
                HqyMerFunctionEnumsV2.USER_SIGN.getCode(),
                bizBehalfPayment.getBehalfCode(),
                userSign,bizBehalfPayment);
        JSONObject obj =JSONObject.parseObject(map.get("result").toString());
        logger.info("{}|reqeust->签约:{}",map.toString());
        if(bizMerchantReceiver1!=null){
            bizMerchantReceiver.setId(bizMerchantReceiver1.getId());
        }
        if("0".equals(obj.get("businessStatus"))){
            //签约成功
            bizMerchantReceiver.setContractStatus("2");
            iBizMerchantReceiverService.saveOrUpdate(bizMerchantReceiver);
            return AjaxResult.success("签约成功","2");
        }else{
            //签约失败
            bizMerchantReceiver.setContractStatus("1");
            String msg = "";
            if("".equals(obj.get("explain")) || null == obj.get("explain") ){
                if("".equals(obj.get("message")) || null == obj.get("message")){
                    msg = "请联系服务商";
                }else{
                    msg = obj.get("message").toString();
                }
            }else{
                msg = obj.get("explain").toString();
            }
            bizMerchantReceiver.setErroMessage(msg);
            iBizMerchantReceiverService.saveOrUpdate(bizMerchantReceiver);
            return AjaxResult.error("签约失败,"+msg);
        }
    }

    //用户信息同步 也就是之前的签约
    public String ylgSign(BizMicroInfo bizMicroInfo){
        JSONObject reqData = new JSONObject();
        reqData.put("username",bizMicroInfo.getMerchIdcardName());
        reqData.put("certNo",bizMicroInfo.getMerchIdcard());
        reqData.put("phone",bizMicroInfo.getMerchBankMobile());
        reqData.put("taskName",bizMicroInfo.getMerchIdcardName()+"信息同步");
        List<String> params = new ArrayList<String>();
        params.add(reqData.toJSONString());
        return YlgUtil.YLG_POST(PosPCommonParamConfig.getPushBatchUser(),params.toString());
    }

    /*
    *创建签约账户
    *
    * */
    @ApiOperation("创建签约账户")
    @PostMapping("/submitCreateUser")
    public AjaxResult submitCreateUser(@RequestBody BizMerchantReceiver bizMerchantReceiver) throws Exception{
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        System.out.println("---------创建签约账户："+bizMerchantReceiver+"-----------------");
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        AjaxResult ajaxResult=AjaxResult.success("创建签约账户");
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        bizMerchantReceiver.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String merchId = bizMerchantService.selectMerchId(bizMerchantReceiver.getUserId().toString());
        bizMerchantReceiver.setMerchId(Long.parseLong(merchId));
        //先查询商户下发收款者是否存在
        // BizMerchantReceiver bizMerchantReceiver1 = iBizMerchantReceiverService.selectBizMerchantReceiverByUserId(bizMerchantReceiver.getUserId());
        /*if (bizMerchantReceiver1 != null ){
            iBizMerchantReceiverService.removeById(bizMerchantReceiver1.getId());
        }*/
        BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(Long.parseLong(merchId));
        //创建签约用户
        Map<String,Object> data =new HashMap<String ,Object>();
        data.put("mobile",bizMicroInfoByMerchId.getMerchBankMobile());
        data.put("idNumber",bizMicroInfoByMerchId.getMerchIdcard());
        data.put("realname",bizMicroInfoByMerchId.getMerchIdcardName());
        //根据商户id查询部门id 查代付类型
//        String dftype =  bizMicroInfoService.getDfTypeByMerchId(bizMerchantReceiver.getUserId().toString());
        // 2024-07-01 两家用同一个代付,  代付主体不同
        return posV1AppMerApiServiceimpl.userSign(bizMicroInfoByMerchId,bizMerchantReceiver.getUserId().toString());
        //判断是否用新代付
//        if("A".equals(dftype)){   //A  是银付通
//            BizMerchantReceiver receiver = new BizMerchantReceiver();
//            receiver.setMerchId(Long.parseLong(merchId));
//            receiver.setUserId(bizMerchantReceiver.getUserId());
//            receiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
//            receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
//            receiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
//            receiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());
//            receiver.setContractStatus("2");
//            receiver.setYlgSignStatus("1");
//            receiver.setCreateTime(format.format(date));
//            //先新增一条商户下发收款者
//            iBizMerchantReceiverService.intserReceiverService(receiver);
//            ajaxResult.put("code","500");
//            ajaxResult.put("msg","签约成功，回到提现页即可提现");
//            return AjaxResult.success(ajaxResult);
//            // // TODO: 2024/4/8 新的签约接口  2024 05 10 废弃
//            String result = ylgSign(bizMicroInfoByMerchId);
//            JSONObject json = JSONObject.parseObject(result);
//            if(json.get("code").equals("0000")){
//                // 签约成功
//                BizMerchantReceiver bizMerchantReceiver1 = iBizMerchantReceiverService.selectBizMerchantReceiverByMerchId(bizMerchantReceiver);
//                if (bizMerchantReceiver1==null){
//                    //查询出该商户
//                    BizMerchantReceiver receiver = new BizMerchantReceiver();
//                    receiver.setMerchId(Long.parseLong(merchId));
//                    receiver.setUserId(bizMerchantReceiver.getUserId());
//                    receiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
//                    receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
//                    receiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
//                    receiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());
//                    receiver.setContractStatus("2");
//                    receiver.setYlgSignStatus("1");
//                    receiver.setCreateTime(format.format(date));
//                    //先新增一条商户下发收款者
//                    iBizMerchantReceiverService.intserReceiverService(receiver);
//                    ajaxResult.put("code","500");
//                    ajaxResult.put("msg","签约成功，回到提现页即可提现");
//                    return AjaxResult.success(ajaxResult);
//                }else {
//                    BizMerchantReceiver receiver = new BizMerchantReceiver();
//                    receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
//                    receiver.setContractStatus("2");
//                    receiver.setYlgSignStatus("1");
//                    iBizMerchantReceiverService.updateReceiver(receiver);
//                    ajaxResult.put("code","500");
//                    ajaxResult.put("msg","签约成功，回到提现页即可提现");
//                    return AjaxResult.success(ajaxResult);
//                }
//            }else{
//                ajaxResult.put("code","500");
//                ajaxResult.put("msg","签约失败:"+json.get("content"));
//                return AjaxResult.success(ajaxResult);
//            }
//        }else{  // B是李志
//            return posV1AppMerApiServiceimpl.userSign(bizMicroInfoByMerchId,bizMerchantReceiver.getUserId().toString());
//        }
//        //签名
//        String sign= SaasSignatureUtil.getSignature(bizAgentidAppkeyDTO);
//        //业务参数（加密数据）
//        String requestBody= AESUtil.encrypt(data,bizAgentidAppkeyDTO.getAppsecret());
//        /*token*/
//        String token= bizMerchantReceiverService.acquireAccessToken(bizAgentidAppkeyDTO);
//        JSONObject submitCreateUser=SaasSignatureUtil.submit(bizAgentidAppkeyDTO,"submitCreateUser",sign,requestBody,token);
//        if(submitCreateUser.getString("code").equals("0000")){
//            String accountId=submitCreateUser.getJSONObject("data").getString("accountId");
//            AjaxResult ajaxResult1=getElectronicContract(accountId,token);
//            BizMerchantReceiver bizMerchantReceiver1 = iBizMerchantReceiverService.selectBizMerchantReceiverByMerchId(bizMerchantReceiver);
//            if (bizMerchantReceiver1==null){
//                //查询出该商户
//                BizMerchantReceiver receiver = new BizMerchantReceiver();
//                receiver.setMerchId(Long.parseLong(merchId));
//                receiver.setUserId(bizMerchantReceiver.getUserId());
//                receiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
//                receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
//                receiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
//                receiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());
//                if (ajaxResult1.get("code").equals("0000")){
//                    receiver.setContractStatus("1");
//                    //receiver.setMerchIdcardBack(bizMerchantReceiver.getMerchIdcardBack());
//                    receiver.setCreateTime(format.format(date));
//                    //先新增一条商户下发收款者
//                    iBizMerchantReceiverService.intserReceiverService(receiver);
//                }else if (ajaxResult1.get("code").equals("5004")){
//                    BizMerchantReceiver bizMerchantReceiver2 = iBizMerchantReceiverService.selectBizMerchantReceiverByMerchId(bizMerchantReceiver);
//                    if (bizMerchantReceiver2==null){
//                        receiver.setContractStatus("2");
//                        //receiver.setMerchIdcardBack(bizMerchantReceiver.getMerchIdcardBack());
//                        receiver.setCreateTime(format.format(date));
//                        //先新增一条商户下发收款者
//                        iBizMerchantReceiverService.intserReceiverService(receiver);
//                        ajaxResult.put("code","500");
//                        ajaxResult.put("msg","签约成功，回到提现页即可提现");
//                        return ajaxResult;
//                    }else {
//                        ajaxResult.put("code","500");
//                        ajaxResult.put("msg","您已经签约成功了，回到提现页即可提现");
//                        return ajaxResult;
//                    }
//                }
//                return AjaxResult.success(ajaxResult1);
//            }else {
//                BizMerchantReceiver receiver = new BizMerchantReceiver();
//                receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
//                receiver.setContractStatus("2");
//                iBizMerchantReceiverService.updateReceiver(bizMerchantReceiver1);
//                ajaxResult.put("code","500");
//                ajaxResult.put("msg","签约成功，回到提现页即可提现");
//                return AjaxResult.success(ajaxResult);
//            }
//        }else if(submitCreateUser.getString("code").equals("5004")){
//            BizMerchantReceiver bizMerchantReceiver1 = iBizMerchantReceiverService.selectBizMerchantReceiverByMerchId(bizMerchantReceiver);
//            if (bizMerchantReceiver1==null){
//                //查询出该商户
//                BizMerchantReceiver receiver = new BizMerchantReceiver();
//                receiver.setMerchId(Long.parseLong(merchId));
//                receiver.setUserId(bizMerchantReceiver.getUserId());
//                receiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
//                receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
//                receiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
//                receiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());
//                receiver.setContractStatus("2");
//                //receiver.setMerchIdcardBack(bizMerchantReceiver.getMerchIdcardBack());
//                receiver.setCreateTime(format.format(date));
//                //先新增一条商户下发收款者
//                Long id= iBizMerchantReceiverService.intserReceiverService(receiver);
//                ajaxResult.put("code","500");
//                ajaxResult.put("msg","签约成功，回到提现页即可提现");
//                return ajaxResult;
//            }else {
//                ajaxResult.put("code","500");
//                ajaxResult.put("msg","您已经签约成功了，回到提现页即可提现");
//                return ajaxResult;
//            }
//        } else {
//            ajaxResult.put("code","500");
//            ajaxResult.put("msg",submitCreateUser.getString("message"));
//            return ajaxResult;
//        }
    }

    /*
    *
    * 电子签约
    * */
    public AjaxResult getElectronicContract(String accountId,String token) throws Exception{
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        System.out.println("---------电子签约：："+accountId+"-----------------");
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        AjaxResult ajaxResult=AjaxResult.success("电子签约");
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        //创建签约用户
        Map<String,Object> data=new HashMap<String,Object>();
        data.put("accountId",accountId);//创建签约用户是返回的accountId
        /*传一个userId,为了获取当前登录人*/
        data.put("notify_url",bizAgentidAppkeyDTO.getNotifyUrl().replace("[userid]",SecurityUtils.getLoginUser().getUser().getUserId().toString()));
        data.put("redirect_url",bizAgentidAppkeyDTO.getRedirectUrl());
        String sign=SaasSignatureUtil.getSignature(bizAgentidAppkeyDTO);
        String requestBodyqy=AESUtil.encrypt(data,bizAgentidAppkeyDTO.getAppsecret());
        JSONObject submitSign=SaasSignatureUtil.submit(bizAgentidAppkeyDTO,"submitSign",sign,requestBodyqy,token);
        if(submitSign.getString("code").equals("0000")){
           String url=submitSign.getJSONObject("data").getString("url");
           String longUrl=submitSign.getJSONObject("data").getString("longUrl");
           String flowId=submitSign.getJSONObject("data").getString("flowId");
           String accountIdReturn=submitSign.getJSONObject("data").getString("accountId");
           ajaxResult.put("url",url);
           ajaxResult.put("longUrl",longUrl);
           ajaxResult.put("flowId",flowId);
           ajaxResult.put("accountIdReturn",accountIdReturn);
            return ajaxResult;
        }else if (submitSign.getString("code").equals("5004")) {
            ajaxResult.put("code","5004");
            ajaxResult.put("msg",submitSign.getString("message"));
            return ajaxResult;
        }else {
            ajaxResult.put("code","500");
            ajaxResult.put("msg",submitSign.getString("message"));
            return ajaxResult;
        }
    }
    /*
    *查看签约状态
    *
    * */
    @ApiOperation("查看签约状态")
    @PostMapping("/getEsign")
    public AjaxResult getEsign(@RequestBody BizMerchantReceiver bizMerchantReceiver) throws Exception{
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        System.out.println("---------查看签约状态：："+bizMerchantReceiver+"-----------------");
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        AjaxResult ajaxResult=AjaxResult.success("查看签约状态");
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        String merchId = bizMerchantService.selectMerchId(bizMerchantReceiver.getUserId().toString());
        bizMerchantReceiver.setMerchId(Long.parseLong(merchId));
        BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(Long.parseLong(merchId));
        //创建签约用户
        Map<String,Object> data =new HashMap<String ,Object>();
        data.put("mobile",bizMicroInfoByMerchId.getMerchBankMobile());
        data.put("idNumber",bizMicroInfoByMerchId.getMerchIdcard());
        data.put("realname",bizMicroInfoByMerchId.getMerchIdcardName());
        //签名
        String sign= SaasSignatureUtil.getSignature(bizAgentidAppkeyDTO);
        //业务参数（加密数据）
        String requestBody= AESUtil.encrypt(data,bizAgentidAppkeyDTO.getAppsecret());
        String token= bizMerchantReceiverService.acquireAccessToken(bizAgentidAppkeyDTO);
        JSONObject submitGetEsign=SaasSignatureUtil.submit(bizAgentidAppkeyDTO,"getEsign",sign,requestBody,token);
        if(submitGetEsign.getString("code").equals("0000")){
            String flowId= submitGetEsign.getJSONObject("data").getString("flow_id");
            String signStatus= submitGetEsign.getJSONObject("data").getString("sign_status");
            String idNumber= submitGetEsign.getJSONObject("data").getString("id_number");
            String companyId= submitGetEsign.getJSONObject("data").getString("company_id");
            String remark= submitGetEsign.getJSONObject("data").getString("remark");
            String notifyType= submitGetEsign.getJSONObject("data").getString("notify_type");
            String downloadUrl= submitGetEsign.getJSONObject("data").getString("download_url");
            String detail= submitGetEsign.getJSONObject("data").getString("detail");
            BizMerchantReceiver bizMerchantReceiver1=new BizMerchantReceiver();
            bizMerchantReceiver1.setDealNo(flowId);
            bizMerchantReceiver1.setContractStatus(signStatus);
            bizMerchantReceiver1.setMerchIdcard(idNumber);
            bizMerchantReceiver1.setCompanyId(companyId);
            bizMerchantReceiver1.setErroMessage(remark);
            bizMerchantReceiver1.setNotifyType(notifyType);
            bizMerchantReceiver1.setDownloadUrl(downloadUrl);
            iBizMerchantReceiverService.updateReceiver(bizMerchantReceiver1);
            Long userId = iBizMerchantReceiverService.selectMerchantReceiverMerchId(idNumber);
            BizMessageRecords bizMessageRecords = new BizMessageRecords();
            bizMessageRecords.setMsgUserId(userId);
            if (signStatus.equals("2")){
                bizMessageRecords.setMsgContent("您已签约成功");
            }else {
                bizMessageRecords.setMsgContent("您签约失败");
            }
            bizMessageRecords.setMsgStatus(0);
            bizMessageRecords.setMsgType(2);
            bizMessageRecords.setReadStatus(0);
            bizMessageRecords.setAdviceType(1);
            bizMessageRecordsService.save(bizMessageRecords);
            ajaxResult.put("code","200");
            ajaxResult.put("data",submitGetEsign.getJSONObject("data"));
            return ajaxResult;
        }else {
            ajaxResult.put("code","500");
            ajaxResult.put("msg",submitGetEsign.getString("message"));
            return ajaxResult;
        }
    }

    @ApiOperation("签约回调")
    @PostMapping("/receiver/{userId}/callBack")
    @Transactional
    public String success(HttpServletRequest request, @RequestParam String requestBody,@PathVariable("userId") String userId) throws Exception {
        System.out.println("---------回调时间：" + new Date() + "-------------------------------------");
        System.out.println("--------------------------------------------------------------------");
        System.out.println("---------签约回调结果" + requestBody + "----------------------------------------");
        System.out.println("--------------------------------------------------------------------");
        System.out.println("---------------------------"+"签约回调结果UserId"+userId+"-----------------------------------------");
        System.out.println("--------------------------------------------------------------------");
        System.out.println("--------------------------------------------------------------------");
        /*解码*/
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(Long.valueOf(userId));
        JSONObject jsonObject=AESUtil.decrypt(requestBody,bizAgentidAppkeyDTO.getAppsecret());//jsonobject
        String flowId= jsonObject.getString("flow_id");
        String signStatus= jsonObject.getString("sign_status");
        String idNumber= jsonObject.getString("id_number");
        String companyId= jsonObject.getString("company_id");
        String remark= jsonObject.getString("remark");
        String notifyType= jsonObject.getString("notify_type");
        String downloadUrl= jsonObject.getString("download_url");
        String detail= jsonObject.getString("detail");
        BizMerchantReceiver bizMerchantReceiver=new BizMerchantReceiver();
        bizMerchantReceiver.setDealNo(flowId);
        bizMerchantReceiver.setContractStatus(signStatus);
        bizMerchantReceiver.setMerchIdcard(idNumber);
        bizMerchantReceiver.setCompanyId(companyId);
        bizMerchantReceiver.setErroMessage(remark);
        bizMerchantReceiver.setNotifyType(notifyType);
        bizMerchantReceiver.setDownloadUrl(downloadUrl);
        iBizMerchantReceiverService.updateReceiver(bizMerchantReceiver);
        Long userId1 = iBizMerchantReceiverService.selectMerchantReceiverMerchId(idNumber);
        BizMessageRecords bizMessageRecords = new BizMessageRecords();
        bizMessageRecords.setMsgUserId(userId1);
        if (signStatus.equals("2")){
            bizMessageRecords.setMsgContent("您已签约成功");
        }else {
            bizMessageRecords.setMsgContent("您签约失败");
        }
        bizMessageRecords.setMsgStatus(0);
        bizMessageRecords.setMsgType(2);
        bizMessageRecords.setReadStatus(0);
        bizMessageRecords.setAdviceType(1);
        bizMessageRecordsService.save(bizMessageRecords);
        return "success";
    }

    /*
    * 风控接口---用来判断能不能提现
    * */
    @PostMapping("/getRiskControl")
    public static AjaxResult getRiskControl(RiskControlDTO riskControlDTO, BizAgentidAppkeyDTO bizAgentidAppkeyDTO, String natchno, String token) throws Exception{
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        System.out.println("---------风控接口：："+riskControlDTO+"-----------------");
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        AjaxResult ajaxResult=AjaxResult.success("风控接口");
        //创建签约用户
        Map<String,Object> data=new HashMap<String,Object>();
        data.put("natchno",natchno);
        data.put("uid",bizAgentidAppkeyDTO.getUid());//账号中UID
        data.put("idcard",riskControlDTO.getIdcard());
        data.put("idtypename","1");
        data.put("inAcctName",riskControlDTO.getInAcctName());
        data.put("inAcctNo",riskControlDTO.getInAcctNo());
        data.put("ccyCode","OTHERBANK");
        data.put("cardType","DC");
        data.put("tranAmount",riskControlDTO.getTranAmount());
        data.put("cardAttribute","C");
        data.put("mobile",riskControlDTO.getMobile());
        String sign= SaasSignatureUtil.getSignature(bizAgentidAppkeyDTO);
        //业务参数（加密数据）
        String requestBody= AESUtil.encrypt(data,bizAgentidAppkeyDTO.getAppsecret());
        JSONObject getRiskControl=SaasSignatureUtil.submit(bizAgentidAppkeyDTO,"getRiskControl",sign,requestBody,token);
        if(getRiskControl.getString("code").equals("0000")){
            int pass=getRiskControl.getJSONObject("data").getInteger("pass");
            String description=getRiskControl.getJSONObject("data").getString("description");
            ajaxResult.put("code",getRiskControl.getString("code"));
            ajaxResult.put("message",getRiskControl.getString("message"));
            ajaxResult.put("pass",pass);
            ajaxResult.put("description",description);
            return ajaxResult;
        }else {
            ajaxResult.put("code","500");
            ajaxResult.put("message",getRiskControl.getString("message"));
            return ajaxResult;
        }
    }

    /*
    * 单笔对私提现
    * */
    @PostMapping("/submitGrantDetail")
    public AjaxResult submitGrantDetail(@RequestBody SubmitGrantDetailDTO submitGrantDetailDTO) throws Exception{
        SysUser user=SecurityUtils.getLoginUser().getUser();
        if(posMachineMapper.getDeptid(user.getUserId())==122){
            return AjaxResult.error("系统升级中。。。。。。。");
        }
        user=posMachineMapper.getUserByUserId(user.getUserId());
        if(user.getWithdraw()!=null&&user.getWithdraw()==0){
            return AjaxResult.error("暂无法提现，请联系客服");
        }

        System.out.println("--------------------------");
        System.out.println("--------------------------");
        System.out.println("---------单笔对私提现：："+submitGrantDetailDTO+"-----------------");
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        AjaxResult ajaxResult=AjaxResult.success("单笔对私提现");
        /*获取编码密钥*/
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        submitGrantDetailDTO.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        /*生成  唯一值*/
        String natchno="ZF"+System.currentTimeMillis()+""+String.format("%04d",new Random().nextInt(9999));
        String merchId = bizMerchantService.selectMerchId(submitGrantDetailDTO.getUserId().toString());
        //查询部门
        String deptId = bizMicroInfoService.getDeptIdByuserId(submitGrantDetailDTO.getUserId().toString());
        //根据商户id查询部门id 查代付类型
        String dftype =  bizMicroInfoService.getDfTypeByMerchId(submitGrantDetailDTO.getUserId().toString());
        BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(Long.parseLong(merchId));
        //判断是否用新代付
        if("A".equals(dftype)){ //A  银付通
//            return walletService.payYLG(submitGrantDetailDTO,bizMicroInfoByMerchId,natchno);
//            return walletService.payFeiShunDLG(bizAgentidAppkeyDTO,submitGrantDetailDTO,bizMicroInfoByMerchId,natchno);
//            if(user.getUserId() != 28l){
//                return AjaxResult.error("系统升级中。请关注后续通知");
//            }
            return posV1AppMerApiServiceimpl.batchPayMent(merchId,submitGrantDetailDTO,dftype,deptId);
        }else{ //  B 李志
            return posV1AppMerApiServiceimpl.batchPayMent(merchId,submitGrantDetailDTO,dftype,deptId);
        }
//        /*获取当前  userid的钱包key*/
//        BizWallet bizWallet= posMachineMapper.selbizWallet(submitGrantDetailDTO.getUserId());
//        /*解密app传过来的   加密过的金额，用来风控接口*/
//         String money= DESHelperUtil.decrypt(bizWallet.getSecretKey(), submitGrantDetailDTO.getCashOutAmount());
//        /*查询签约状态  0待签约；1-签约中；2-已签约；3-失败 4-拒签*/
//        BizMerchantReceiver bizMerchantReceiver= iBizMerchantReceiverService.selectReceiverMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard(),bizMicroInfoByMerchId.getMerchId());
//        if (bizMerchantReceiver==null || !bizMerchantReceiver.getContractStatus().equals("2")){
//            return AjaxResult.error("未签约或签约未成功");
//        }
//        RiskControlDTO riskControlDTO=new RiskControlDTO();
//        riskControlDTO.setIdcard(bizMicroInfoByMerchId.getMerchIdcard());
//        riskControlDTO.setInAcctName(bizMicroInfoByMerchId.getMerchIdcardName());
//        riskControlDTO.setMobile(bizMicroInfoByMerchId.getMerchBankMobile());
//        riskControlDTO.setInAcctNo(bizMicroInfoByMerchId.getMerchBankCardno());
//        riskControlDTO.setTranAmount(money);
//        /*风控接口*/
//        String token= bizMerchantReceiverService.acquireAccessToken(bizAgentidAppkeyDTO);
//        AjaxResult ajaxResultRiskControl= getRiskControl(riskControlDTO,bizAgentidAppkeyDTO,natchno,token);
//        String code=ajaxResultRiskControl.get("code").toString();
//        String message=ajaxResultRiskControl.get("message").toString();
//        if (code.equals("0000") && message.equals("SUCCESS")){
//            // 提现预支付
//            AjaxResult ajaxResult1 = walletService.payXinLongDLG(bizAgentidAppkeyDTO,submitGrantDetailDTO,bizMicroInfoByMerchId,natchno);
//            return ajaxResult1;
//        }else {
//            ajaxResult.put("code","500");
//            ajaxResult.put("msg",message);
//            return ajaxResult;
//        }
    }
    @GetMapping("/tst")
    public AjaxResult test() throws Exception {
        /*获取编码密钥*/
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(4069l);

        JSONObject jsonObject=walletService.getSearchMer(bizAgentidAppkeyDTO);

        return AjaxResult.success(jsonObject);
    }
    @ApiOperation("提现回调")
    @PostMapping("receiver/tx/{userId}/callBack")
    @Transactional
    public String txSuccess(HttpServletRequest request, @RequestParam String requestBody,@PathVariable("userId")String userId) throws Exception {
        System.out.println("---------回调时间：" + new Date() + "-------------------------------------");
        System.out.println("--------------------------------------------------------------------");
        System.out.println("---------提现回调结果" + requestBody + "----------------------------------------");
        System.out.println("---------------------------"+"提现回调结果UserId"+userId+"-----------------------------------------");
        System.out.println("--------------------------------------------------------------------");
        System.out.println("--------------------------------------------------------------------");
        System.out.println("--------------------------------------------------------------------");
        /*解码*/
        /*获取编码密钥*/
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(Long.valueOf(userId));
        JSONObject jsonObject = AESUtil.decrypt(requestBody,bizAgentidAppkeyDTO.getAppsecret());//jsonobject
        String callBackState = walletService.deliverapiCallbackXinLongDLG(jsonObject);
        return callBackState;
    }
    @ApiOperation("查询总余额")
    @PostMapping("/queryBalance")
    public BigDecimal queryBalance(Long userId) throws Exception {
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(userId);
        Map<String,Object> data=new HashMap<String,Object>();
        data.put("uid",bizAgentidAppkeyDTO.getUid());
        String sign=SaasSignatureUtil.getSignature(bizAgentidAppkeyDTO);
        String requestBodyYe=AESUtil.encrypt(data,bizAgentidAppkeyDTO.getAppsecret());
        String token= bizMerchantReceiverService.acquireAccessToken(bizAgentidAppkeyDTO);
        BigDecimal bigDecimal=new BigDecimal("0.00");
        JSONObject submitBalance=SaasSignatureUtil.submit(bizAgentidAppkeyDTO,"getBalance",sign,requestBodyYe,token);
        if(submitBalance.getString("code").equals("0000")) {
//            String uid = submitBalance.getJSONObject("data").getString("uid");//合作方业务平台 ID
            String balance = submitBalance.getJSONObject("data").getString("balance");//账户余额
            if(StringUtils.isNotBlank(balance)){
                bigDecimal=new BigDecimal(balance);
            }
            System.out.println("账户余额  "+balance );
        }
        return bigDecimal;
    }

//    @PostMapping("/echoReceiver")
    @Transactional
    public AjaxResult echoReceiverNew(@RequestBody BizMerchant bizMerchant){
        AjaxResult ajaxResult = AjaxResult.success("查询商户是否签约");
        //根据商户id查询部门id 查代付类型
        BizMerchantReceiver bizMerchantReceiver;
        String deptId = bizMicroInfoService.getDeptIdByuserId(bizMerchant.getUserId().toString());
        String dftype =  bizMicroInfoService.getDfTypeByMerchId(bizMerchant.getUserId().toString());
        bizMerchant.setDeptId(deptId);
        if("B".equals(dftype)){
            bizMerchantReceiver = bizMerchantService.selectBizMerchantReceiverTypeB(bizMerchant);
        }else{
            bizMerchantReceiver =  bizMerchantService.selectBizMerchantReceiver(bizMerchant);
        }
        if("B".equals(dftype)){
            if (bizMerchantReceiver == null){
                ajaxResult.put("data","0");
                ajaxResult.put("ret_msg","商户待签约");
                return ajaxResult;
            }
            if (bizMerchantReceiver.getContractStatus().equals("0")){
                ajaxResult.put("data","0");
                ajaxResult.put("ret_msg","商户待签约");
                return ajaxResult;
            }else if(bizMerchantReceiver.getContractStatus().equals("1")){
                ajaxResult.put("data","1");
                ajaxResult.put("ret_msg","商户签约中");
                return ajaxResult;
            }else if (bizMerchantReceiver.getContractStatus().equals("3")){
                ajaxResult.put("data","3");
                ajaxResult.put("ret_msg","商户签约失败");
                return ajaxResult;
            }else if (bizMerchantReceiver.getContractStatus().equals("4")){
                ajaxResult.put("data","4");
                ajaxResult.put("ret_msg","商户拒签");
                return ajaxResult;
            }else {
                ajaxResult.put("data","2");
                ajaxResult.put("ret_msg","商户已签约");
                return ajaxResult;
            }
        }else{
            String merchId = bizMerchantService.selectMerchId(bizMerchant.getUserId().toString());
            BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(Long.parseLong(merchId));
            if (bizMerchantReceiver == null){
                BizMerchantReceiver receiver = new BizMerchantReceiver();
                receiver.setMerchId(Long.parseLong(merchId));
                receiver.setUserId(bizMerchant.getUserId());
                receiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
                receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
                receiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
                receiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());
                receiver.setContractStatus("2");
                Date date=new Date();
                SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                receiver.setCreateTime(format.format(date));
                //先新增一条商户下发收款者
                iBizMerchantReceiverService.intserReceiverService(receiver);
                ajaxResult.put("data","2");
                ajaxResult.put("ret_msg","商户已签约");
                return ajaxResult;
            }else {
                if(!bizMerchantReceiver.getContractStatus().equals("2")){
                    BizMerchantReceiver receiver = new BizMerchantReceiver();
                    receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
                    receiver.setContractStatus("2");
                    iBizMerchantReceiverService.updateReceiver(receiver);
                }
                ajaxResult.put("data","2");
                ajaxResult.put("ret_msg","商户已签约");
                return ajaxResult;
            }
        }

    }

    /*
     *创建签约账户
     *
     * */
    @ApiOperation("创建签约账户")
//    @PostMapping("/submitCreateUser")
    public AjaxResult submitCreateUserNew(@RequestBody BizMerchantReceiver bizMerchantReceiver) throws Exception{
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        System.out.println("---------创建签约账户："+bizMerchantReceiver+"-----------------");
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        AjaxResult ajaxResult=AjaxResult.success("创建签约账户");
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        bizMerchantReceiver.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String merchId = bizMerchantService.selectMerchId(bizMerchantReceiver.getUserId().toString());
        bizMerchantReceiver.setMerchId(Long.parseLong(merchId));
        BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(Long.parseLong(merchId));
        //根据商户id查询部门id 查代付类型
        String dftype =  bizMicroInfoService.getDfTypeByMerchId(bizMerchantReceiver.getUserId().toString());
        //判断是否用新代付
        if("B".equals(dftype)){
            return posV1AppMerApiServiceimpl.userSign(bizMicroInfoByMerchId,bizMerchantReceiver.getUserId().toString());
        }
        BizMerchantReceiver bizMerchantReceiver1 = iBizMerchantReceiverService.selectBizMerchantReceiverByMerchId(bizMerchantReceiver);
        if (bizMerchantReceiver1==null){
            //查询出该商户
            BizMerchantReceiver receiver = new BizMerchantReceiver();
            receiver.setMerchId(Long.parseLong(merchId));
            receiver.setUserId(bizMerchantReceiver.getUserId());
            receiver.setMerchName(bizMicroInfoByMerchId.getMerchIdcardName());
            receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
            receiver.setMerchBankMobile(bizMicroInfoByMerchId.getMerchBankMobile());
            receiver.setMerchBankCardno(bizMicroInfoByMerchId.getMerchBankCardno());

            receiver.setContractStatus("2");
            //receiver.setMerchIdcardBack(bizMerchantReceiver.getMerchIdcardBack());
            receiver.setCreateTime(format.format(date));
            //先新增一条商户下发收款者
            iBizMerchantReceiverService.intserReceiverService(receiver);
            ajaxResult.put("code","500");
            ajaxResult.put("msg","签约成功，回到提现页即可提现");
            return AjaxResult.success(ajaxResult);
        }else {
            BizMerchantReceiver receiver = new BizMerchantReceiver();
            receiver.setMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard());
            receiver.setContractStatus("2");
            iBizMerchantReceiverService.updateReceiver(receiver);
            ajaxResult.put("code","500");
            ajaxResult.put("msg","签约成功，回到提现页即可提现");
            return AjaxResult.success(ajaxResult);
        }
    }
//    @PostMapping("/submitGrantDetail")
    public AjaxResult submitGrantDetailNew(@RequestBody SubmitGrantDetailDTO submitGrantDetailDTO) throws Exception{
        SysUser user=SecurityUtils.getLoginUser().getUser();
        if(posMachineMapper.getDeptid(user.getUserId())==122){
            return AjaxResult.error("系统升级中。。。。。。。");
        }
        user=posMachineMapper.getUserByUserId(user.getUserId());
        if(user.getWithdraw()!=null&&user.getWithdraw()==0){
            return AjaxResult.error("暂无法提现，请联系客服");
        }
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        System.out.println("---------单笔对私提现：："+submitGrantDetailDTO+"-----------------");
        System.out.println("--------------------------");
        System.out.println("--------------------------");
        AjaxResult ajaxResult=AjaxResult.success("单笔对私提现");
        /*获取编码密钥*/
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        submitGrantDetailDTO.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        /*生成  唯一值*/
        String natchno="ZF"+System.currentTimeMillis()+""+String.format("%04d",new Random().nextInt(9999));
        String merchId = bizMerchantService.selectMerchId(submitGrantDetailDTO.getUserId().toString());
        //查询部门
        String deptId = bizMicroInfoService.getDeptIdByuserId(submitGrantDetailDTO.getUserId().toString());
        //根据商户id查询部门id 查代付类型
        String dftype =  bizMicroInfoService.getDfTypeByMerchId(submitGrantDetailDTO.getUserId().toString());
        //判断是否用新代付
        if("B".equals(dftype)){
            return posV1AppMerApiServiceimpl.batchPayMent(merchId,submitGrantDetailDTO,dftype,deptId);
        }
        /*获取当前  userid的钱包key*/
        BizWallet bizWallet= posMachineMapper.selbizWallet(submitGrantDetailDTO.getUserId());
        /*解密app传过来的   加密过的金额，用来风控接口*/
//        String money= DESHelperUtil.decrypt(bizWallet.getSecretKey(), submitGrantDetailDTO.getCashOutAmount());
        BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(Long.parseLong(merchId));
        /*查询签约状态  0待签约；1-签约中；2-已签约；3-失败 4-拒签*/
        BizMerchantReceiver bizMerchantReceiver= iBizMerchantReceiverService.selectReceiverMerchIdcard(bizMicroInfoByMerchId.getMerchIdcard(),bizMicroInfoByMerchId.getMerchId());
        if (bizMerchantReceiver==null || !bizMerchantReceiver.getContractStatus().equals("2")){
            return AjaxResult.error("未签约或签约未成功");
        }
        return walletService.payFeiShunDLG(bizAgentidAppkeyDTO,submitGrantDetailDTO,bizMicroInfoByMerchId,natchno);
    }


    public static void main(String[] args) {
        String str = "businessType=1&dataJson=%7B%22bindDate%22%3A1622621492322%2C%22createTime%22%3A1572330523203%2C%22directPromoterId%22%3A%2288001029%22%2C%22idCardNoMask%22%3A%22362330****0012%22%2C%22merchantId%22%3A%2288001097%22%2C%22merchantName%22%3A%22string%22%2C%22merchantPhoneNoMask%22%3A%2217999990020%22%2C%22policyNo%22%3A%22100701%22%2C%22productNo%22%3A%221000780%22%2C%22promoterId%22%3A%2288001029%22%2C%22sn%22%3A%22hymsfff0018%22%2C%22terminalId%22%3A%2229009849%22%7D&mac=NtUlqGq7Rm8CJBAGtzXhiH8Ebw%2B18rPs%2FvEG4Vo1IZqfhEcDcvn9XdrMESVLf2dr7i3A5nBIHX6g%0ABNM3Z9uMPbeg8fdi1LXubqlVNPkyJZrzGGrFvHVkSkmM0vq7bHDXxCyLIdSKojw1pzCrDwvaUWh7%0A3Td5QC%2F%2Btd1s%2F%2B93sh4%3D";
        System.out.println(URLDecoder.decode(str));
    }


    /**
     * 出款结果异步通知接口（notifyPayment）
     * @param
     * @return
     */
    @ApiOperation("龙支付家   出款结果异步通知接口")
    @PostMapping("/notifyPayment")
    public String notifyPayment(@RequestBody String requestJson) throws Exception {
        System.out.println("----------异步接口回调中-----------");
        if(requestJson != null){
            String code = "860141210603821";
            return bizMicroInfoService.notifyPayment(requestJson,code);
        }else{
            return "FAILURE";
        }
    }


    @PostMapping("/eachOneSignature")
    public AjaxResult eachOneSignature(){
        List<BizMerchantReceiver> lists = iBizMerchantReceiverService.getEachOne();
        for(BizMerchantReceiver receiver : lists){
            try{
                BizMerchant bizMerchant = bizMerchantService.getMerchantByMerchId(receiver.getMerchId());
                BizMicroInfo bizMicroInfoByMerchId = bizMicroInfoService.getBizMicroInfoByMerchId(receiver.getMerchId());
                goSign(bizMicroInfoByMerchId,bizMerchant.getUserId(),receiver,"117");
            }catch (Exception e){
                System.out.println(receiver.getUserId()+":"+e.getMessage());
            }

        }
        return AjaxResult.success();
    }
}
